<template>
  <div>
    <div class="fileUploadBtn">
      <!-- <Image :url="modelValue" v-if="modelValue"/> -->
      {{txt}}
      <input type="file" @change="changeFn($event)" :name="name" :disabled="disabled" ref="fileEle" />
    </div>
    <ul class="fileListbox">
        <li v-for="(dt,index) in fileList" :key="dt.url">
          <div class="name">{{ dt.name }}</div>
          <van-icon name="cross" color="green" @click="delFile(index)"/>
        </li>
    </ul>
  </div>
</template>

<script>
import Request from "@/utils/request";
import Image from "cps/public/image"
import { Toast,Icon as vanIcon} from 'vant';
export default {
  props: {
    modelValue:Array,
    name: {
      type: String,
      default: () => "file",
    },
    disabled: {
      type: Boolean,
      default() {
        return false; // 默认
      },
    },
    txt: {
      type: String,
      default: () => "添加附件",
    },
  },
  components:{
      vanIcon
  },
  data() {
    return {
      fileList:[]
    };
  },
  watch: {
      modelValue(newValue, oldValue) {
          this.fileList = newValue
      }
  },
  created() {
    this.fileList = this.modelValue
  },
  methods: {
    async changeFn(e) {
      var file = e.target.files[0];
      const fdata = this.fileList.find(item =>item.name == file.name)
      if(fdata){
        return Toast('该文件已存在，请重新选择！')
      }
      let fromData = new FormData();
      fromData.append("file", file);
      fromData.append("fileName", file.name); 
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      let upUrl = "https://ask-api.ej12366.video/app/file/upload";

      Request
        .post(upUrl, fromData, config)
        .then((res) => {
            this.fileList.push(res.data.data)
            this.$emit('update:modelValue', this.fileList)
            this.$refs.fileEle.value = ''
        })
        .catch((err) => {
          console.log(err);
        });
     
    },
    delFile(index){
        this.fileList.splice(index,1)
        this.$emit('update:modelValue', this.fileList)
    }
  },
};
</script>

<style lang="scss" scoped>
  .fileUploadBtn{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 180px;
    height: 60px;
    position: relative;
    z-index: 10;
    font-size: 26px;
    color: #fff;
    background: rgba(18, 18, 243,0.7);
    border-radius: 10px;
    input{
      position: absolute;
      z-index: 11;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      border: 0;
      opacity: 0;
    }
    
  }
  .fileListbox{
      padding: 0;
      margin: 0;
      list-style: none;
      li{
        display: flex;
        align-items: center;
        padding: 20px;
        background: #fff;
        margin: 20px 0 0 0;
        .name{
          flex: 1;
          flex-shrink: 0;
        }
      }
    }
</style>
